<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=yes">
    <title>图片加载测试</title>
    </title>
    <style>
        body {
            background-color: #000;
        }

        main {
            overflow: auto;
            width: 60vw;
            height: 90vh;
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <main id="content"></main>

    <script>
        const main = document.querySelector('#content')

        const imgURL = [
            'https://img0.baidu.com/it/u=3250535843,1965525668&fm=26&fmt=auto',
            'https://img0.baidu.com/it/u=2951932146,1439978327&fm=26&fmt=auto',
            'https://img0.baidu.com/it/u=1254221411,3657735663&fm=26&fmt=auto',
            'https://img0.baidu.com/it/u=1772231450,2366294170&fm=26&fmt=auto',
            'https://img1.baidu.com/it/u=1125257932,69992268&fm=26&fmt=auto',
            'https://img0.baidu.com/it/u=52369599,1673824363&fm=26&fmt=auto'
        ]

        const imgArr = []

        // 从网上加载几个奥特曼图片
        for (const i of imgURL) {
            const img = new Image()

            img.src = `${i}`
            img.title = '奥特曼'
            img.alt = '奥特曼'

            imgArr.push(img)

            main.appendChild(img)
        }

        // 需要获取所有图片的宽高

        // 图片加载是一个异步请求的操作
        // 如果不使用异步写法 可能无法同步获取到图片的宽高
        // 使用promise 就可以在所有图片加载完成之后 获取到对应图片的信息了
        const imgPro = []

        imgArr.forEach((img, index) => {
            const p = new Promise(done => {
                img.onload = () => {
                    done({
                        index,
                        width: img.width,
                        height: img.height
                    })
                }
            })
            imgPro.push(p)
        })

        Promise.all(imgPro).then(data => console.log(data))

        // 获取加载最快的那张图片的信息
        Promise.race(imgPro).then(data => console.log(data))
    </script>
</body>

</html>